import {reqCartList, reqdeleteCartById,reqUpdateCheckedById} from '@/api'
const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, list) {
        state.cartList = list
    }
}

const actions={
    // 获取购物车列表的数组
    async getCartList({commit}) {
       let result =  await reqCartList()
       if(result.code == 200) {
        commit('GETCARTLIST', result.data)
       }
    },
    // 删除购物车某一个产品
    async deleteCartListBySkuId({commit}, skuId) {
        let result =  await reqdeleteCartById(skuId)
        if(result.code == 200) {
         return "ok"
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //  修改购物车某一个产品的选中状态
    async updateCheckedById({commit}, {skuId, isChecked}) {
       let result =  await reqUpdateCheckedById(skuId, isChecked)
       if(result.code == 200) {
        return "ok"
       } else{
        return Promise.reject(new Error('faile'))
       }
    },
    // 删除全部勾选的产品
    deleteAllCheckedCart({dispatch, getters}) {
        // console.log(context.getters.cartList.cartInfoList);
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
           let promise =  item.isChecked == 1? dispatch('deleteCartListBySkuId', item.skuId) : ''
           PromiseAll.push(promise)
        });
        
        return Promise.all(PromiseAll)
    },
    // 修改全部商品的状态
    updateAllCartChecked({dispatch, getters}, isChecked) {
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedById', {skuId: item.skuId,isChecked: isChecked})
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
}

export default {
    state, mutations, actions, getters
}
